import 'package:aichat_flutter_wallet/kai_print.dart';
import 'package:aichat_flutter_wallet/module_common/mpc_help/mpcManager.dart';
import 'package:aichat_flutter_wallet/module_common/network/chains_type/ethchain.dart';
import 'package:aichat_flutter_wallet/module_common/network/http_chain_list.dart';
import 'package:aichat_flutter_wallet/module_common/utils/auth.dart';
import 'package:aichat_flutter_wallet/module_common/utils/util.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/dialog_utils.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/log/log.dart';
import 'package:lib_web3/lib_web3_method.dart';

import '../mpc_help/chainListTool.dart';

class Sign {
  static getErc20Gas(rpcUrl, type, transaction,String symbol) async {
    try {
      if (type == 'native') transaction = '';
      Map<String, dynamic>? res =
          await ChainListTool.getErc20Gas( rpcUrl: rpcUrl, transaction: transaction, symbol: symbol);
      if (res == null) return {'gas': 0, 'gasPrice': 0};
      return {
        'gas': (type == 'native' ||
                (transaction != '' && transaction["gas"] != null))
            ? int.parse(res['gas'])
            : (int.parse(res['gas']) * 2.5).floor(),
        'gasPrice': int.parse(res['gasPrice'])
      };
    } catch (e) {
      return {'gas': 0, 'gasPrice': 0};
    }
  }

  static verifyPwd() async {
    // BuildContext context = NavKey.getContext();
    bool pass = await Authentication().startLocalAuth(
        showPasswordError: false,
        callBackError: () {
          DialogUtils.showToast(
              message: 'Verification password error', position: 'top');
          // Toast.show(context,
          //     status: '0',
          //     position: Dpositon.top,
          //     message: "Verification password error",
          //     duration: Duration(milliseconds: 3000));
        });
    if (!pass) return false;
    return true;
  }

  static EthSgin(ETHTransaction ethTransaction, Chain chain,
      {Function? successCallback,
      Function? errCallback,
      bool status = false}) async {
    int chainId = chain.evmInfo!.chainId;
    String rpc =
        ObjectBox().nodeInfoModel.getSelectedNodeInfo(chain.shortName).url;
    String type = isMain(ethTransaction) ? 'native' : 'token20';
    String contract = isMain(ethTransaction) ? '' : (ethTransaction.to ?? '');
    Sign.EthSgin2(
      rpc,
      chainId,
      ethTransaction,
      contract,
      type,
    ).then((data) async {
      var salt = await SP().getRandomSalt();
      if (salt == null) salt = await HttpChainList().getSaltByUrl();
      // 盐丢失
      if (salt == null) {
        return DialogUtils.showToast(message: 'Salt lost', position: 'top');
      }
      List<String> keyList = await WalletCheck.checkSignKey();

      if (keyList.length < 2) {
        return DialogUtils.showToast(
            message: 'Please check wallet status', position: 'top');
      }
      String signStr =
          await mpcTool().signTx(data['tx'], keyList[0], keyList[1], salt);
      if (signStr == 'invalid padding' || signStr == '')
        return errCallback?.call('Signature failed');
      Sign.SingSend(rpc, chainId, data['tran'], signStr, status).then((txId) {
        Log.logger.e('txIdtxIdtxIdtxId$txId');
        successCallback?.call(txId);
      }).catchError((e) {
        Log.logger.e('eeeeeeeeeeeeeeeeeeeeeeeeeeeeee', error: e);
        errCallback?.call(e);
      });
    }).catchError((e) {
      Log.logger.e('eeeeeeeeeeeeeeeeee', error: e);
      errCallback?.call(e);
    });
  }

  static EthSginData(String signData,
      {Function? successCallback, Function? errCallback}) async {
    FlutterWeb3.ethSignData(signData).then((data) async {
      var salt = await SP().getRandomSalt();
      if (salt == null) salt = await HttpChainList().getSaltByUrl();
      // 盐丢失
      if (salt == null) return errCallback?.call('Salt lost');
      List<String> keyList = await WalletCheck.checkSignKey();
      if (keyList.length < 2)
        return errCallback?.call('Please check wallet status');
      String signStr =
          await mpcTool().signTx(data!, keyList[0], keyList[1], salt);
      if (signStr == 'invalid padding' || signStr == '')
        return errCallback?.call('Signature failed');
      successCallback?.call('0x' + signStr);
    }).catchError((e) {
      Log.logger.e('flutter show error', error: e);
      errCallback?.call(e);
    });
  }

  static EthSgin2(rpc, int chainId, ethTransaction, contract, type) async {
    try {
      Map<String, dynamic> tran = {
        "from": ethTransaction.from,
        "to": ethTransaction.to,
        "value": ethTransaction.value,
        "gas": ethTransaction.gas,
        "gasPrice": ethTransaction.gasPrice,
        "nonce": ethTransaction.nonce,
        "data": ethTransaction.data,
      };
      Map<String, dynamic>? data =
          await ChainListTool.getWeb3SignTx(rpc, chainId, tran, contract, type);
      return data;
    } catch (e) {
      throw e;
    }
  }

  static Future SingSend(String rpc, int chainId, txInfo,
      String signInfo, bool status) async {
    try {
      String data = await ChainListTool.ethSignSendTransaction(
          rpc, chainId, txInfo, signInfo,
          status: status);
      return data;
    } catch (e) {
      Log.logger.e('SingSend error ::::: $e');
      throw e.toString();
    }
  }

  static bool isMain(ethTransaction) {
    return ethTransaction!.data == null ||
        ethTransaction!.data!.isEmpty ||
        ethTransaction!.data == '0x';
  }
}
